using MediatR;
using Microsoft.AspNetCore.Mvc;
using S.M.SmartMedical.API.Read.Application.Query;
using S.M.SmartMedical.Domain.Enums;
using S.M.SmartMedical.ErrorCode;

namespace S.M.SmartMedical.API.Read.Controllers;

/// <summary>
/// 开单申请查询控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class OrderApplicationController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<OrderApplicationController> _logger;

    public OrderApplicationController(IMediator mediator, ILogger<OrderApplicationController> logger)
    {
        _mediator = mediator;
        _logger = logger;
    }

    /// <summary>
    /// 获取开单申请列表（分页）
    /// </summary>
    /// <param name="userId">用户ID（可选）</param>
    /// <param name="hospitalAreaId">院区ID（可选）</param>
    /// <param name="status">申请状态（可选）</param>
    /// <param name="applicationNumber">申请编号（可选，支持模糊搜索）</param>
    /// <param name="startDate">开始日期（可选）</param>
    /// <param name="endDate">结束日期（可选）</param>
    /// <param name="pageIndex">页码，从1开始，默认为1</param>
    /// <param name="pageSize">每页大小，默认为10</param>
    /// <param name="sortField">排序字段（可选）：CreateTime, TotalAmount, Status</param>
    /// <param name="sortAscending">排序方向：true为升序，false为降序，默认为false</param>
    /// <returns>开单申请列表</returns>
    [HttpGet]
    [ProducesResponseType(typeof(APIResult<PagedResult<OrderApplicationDto>>), 200)]
    public async Task<ActionResult<APIResult<PagedResult<OrderApplicationDto>>>> GetOrderApplications(
        [FromQuery] int? userId = null,
        [FromQuery] int? hospitalAreaId = null,
        [FromQuery] OrderApplicationStatus? status = null,
        [FromQuery] string? applicationNumber = null,
        [FromQuery] DateTime? startDate = null,
        [FromQuery] DateTime? endDate = null,
        [FromQuery] int pageIndex = 1,
        [FromQuery] int pageSize = 10,
        [FromQuery] string? sortField = "CreateTime",
        [FromQuery] bool sortAscending = false)
    {
        try
        {
            _logger.LogInformation("接收到获取开单申请列表请求，用户ID：{UserId}，院区ID：{HospitalAreaId}，状态：{Status}，页码：{PageIndex}，页大小：{PageSize}", 
                userId, hospitalAreaId, status, pageIndex, pageSize);

            // 验证分页参数
            if (pageIndex < 1)
            {
                pageIndex = 1;
            }
            if (pageSize < 1 || pageSize > 100)
            {
                pageSize = 10;
            }

            var query = new GetOrderApplicationsQuery
            {
                UserId = userId,
                HospitalAreaId = hospitalAreaId,
                Status = status,
                ApplicationNumber = applicationNumber,
                StartDate = startDate,
                EndDate = endDate,
                PageIndex = pageIndex,
                PageSize = pageSize,
                SortField = sortField,
                SortAscending = sortAscending
            };

            var result = await _mediator.Send(query);

            _logger.LogInformation("获取开单申请列表成功，总数：{TotalCount}，当前页：{PageIndex}，页大小：{PageSize}", 
                result.Data?.TotalCount ?? 0, pageIndex, pageSize);

            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取开单申请列表时发生异常，用户ID：{UserId}", userId);
            
            return Ok(new APIResult<PagedResult<OrderApplicationDto>>
            {
                Code = APIEnum.Fail,
                Message = $"获取开单申请列表失败：{ex.Message}",
                Data = new PagedResult<OrderApplicationDto>
                {
                    Items = new List<OrderApplicationDto>(),
                    TotalCount = 0,
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    TotalPages = 0
                }
            });
        }
    }

    /// <summary>
    /// 获取指定用户的开单申请列表
    /// </summary>
    /// <param name="userId">用户ID</param>
    /// <param name="status">申请状态（可选）</param>
    /// <param name="pageIndex">页码，从1开始，默认为1</param>
    /// <param name="pageSize">每页大小，默认为10</param>
    /// <returns>开单申请列表</returns>
    [HttpGet("user/{userId}")]
    [ProducesResponseType(typeof(APIResult<PagedResult<OrderApplicationDto>>), 200)]
    public async Task<ActionResult<APIResult<PagedResult<OrderApplicationDto>>>> GetUserOrderApplications(
        [FromRoute] int userId,
        [FromQuery] OrderApplicationStatus? status = null,
        [FromQuery] int pageIndex = 1,
        [FromQuery] int pageSize = 10)
    {
        try
        {
            _logger.LogInformation("接收到获取用户开单申请列表请求，用户ID：{UserId}，状态：{Status}，页码：{PageIndex}，页大小：{PageSize}", 
                userId, status, pageIndex, pageSize);

            // 验证分页参数
            if (pageIndex < 1)
            {
                pageIndex = 1;
            }
            if (pageSize < 1 || pageSize > 100)
            {
                pageSize = 10;
            }

            var query = new GetOrderApplicationsQuery
            {
                UserId = userId,
                Status = status,
                PageIndex = pageIndex,
                PageSize = pageSize,
                SortField = "CreateTime",
                SortAscending = false
            };

            var result = await _mediator.Send(query);

            _logger.LogInformation("获取用户开单申请列表成功，用户ID：{UserId}，总数：{TotalCount}", 
                userId, result.Data?.TotalCount ?? 0);

            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取用户开单申请列表时发生异常，用户ID：{UserId}", userId);
            
            return Ok(new APIResult<PagedResult<OrderApplicationDto>>
            {
                Code = APIEnum.Fail,
                Message = $"获取用户开单申请列表失败：{ex.Message}",
                Data = new PagedResult<OrderApplicationDto>
                {
                    Items = new List<OrderApplicationDto>(),
                    TotalCount = 0,
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    TotalPages = 0
                }
            });
        }
    }

    /// <summary>
    /// 获取开单申请详情
    /// </summary>
    /// <param name="id">申请ID</param>
    /// <param name="userId">用户ID（可选，用于权限验证）</param>
    /// <returns>开单申请详情</returns>
    [HttpGet("{id}")]
    [ProducesResponseType(typeof(APIResult<OrderApplicationDetailDto>), 200)]
    public async Task<ActionResult<APIResult<OrderApplicationDetailDto>>> GetOrderApplicationDetail(
        [FromRoute] int id,
        [FromQuery] int? userId = null)
    {
        try
        {
            _logger.LogInformation("接收到获取开单申请详情请求，申请ID：{Id}，用户ID：{UserId}", id, userId);

            var query = new GetOrderApplicationDetailQuery
            {
                Id = id,
                UserId = userId
            };

            var result = await _mediator.Send(query);

            if (result.Code == APIEnum.OK)
            {
                _logger.LogInformation("获取开单申请详情成功，申请ID：{Id}，项目数量：{ItemCount}", 
                    id, result.Data?.Items?.Count ?? 0);
            }
            else
            {
                _logger.LogWarning("获取开单申请详情失败，申请ID：{Id}，错误：{Message}", id, result.Message);
            }

            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取开单申请详情时发生异常，申请ID：{Id}", id);
            
            return Ok(new APIResult<OrderApplicationDetailDto>
            {
                Code = APIEnum.Fail,
                Message = $"获取开单申请详情失败：{ex.Message}",
                Data = default(OrderApplicationDetailDto)!
            });
        }
    }

    /// <summary>
    /// 获取开单申请状态统计
    /// </summary>
    /// <param name="userId">用户ID（可选）</param>
    /// <param name="hospitalAreaId">院区ID（可选）</param>
    /// <param name="startDate">开始日期（可选）</param>
    /// <param name="endDate">结束日期（可选）</param>
    /// <returns>状态统计信息</returns>
    [HttpGet("statistics/status")]
    [ProducesResponseType(typeof(APIResult<Dictionary<string, int>>), 200)]
    public async Task<ActionResult<APIResult<Dictionary<string, int>>>> GetOrderApplicationStatusStatistics(
        [FromQuery] int? userId = null,
        [FromQuery] int? hospitalAreaId = null,
        [FromQuery] DateTime? startDate = null,
        [FromQuery] DateTime? endDate = null)
    {
        try
        {
            _logger.LogInformation("接收到获取开单申请状态统计请求，用户ID：{UserId}，院区ID：{HospitalAreaId}", userId, hospitalAreaId);

            // 获取各状态的申请数量
            var statistics = new Dictionary<string, int>();
            var statuses = Enum.GetValues<OrderApplicationStatus>();

            foreach (var status in statuses)
            {
                var query = new GetOrderApplicationsQuery
                {
                    UserId = userId,
                    HospitalAreaId = hospitalAreaId,
                    Status = status,
                    StartDate = startDate,
                    EndDate = endDate,
                    PageIndex = 1,
                    PageSize = 1 // 只需要总数，不需要具体数据
                };

                var result = await _mediator.Send(query);
                var statusName = GetStatusDescription(status);
                statistics[statusName] = result.Data?.TotalCount ?? 0;
            }

            _logger.LogInformation("获取开单申请状态统计成功，统计项数：{Count}", statistics.Count);

            return Ok(new APIResult<Dictionary<string, int>>
            {
                Code = APIEnum.OK,
                Message = "获取统计信息成功",
                Data = statistics
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取开单申请状态统计时发生异常，用户ID：{UserId}", userId);
            
            return Ok(new APIResult<Dictionary<string, int>>
            {
                Code = APIEnum.Fail,
                Message = $"获取统计信息失败：{ex.Message}",
                Data = new Dictionary<string, int>()
            });
        }
    }

    /// <summary>
    /// 获取状态描述
    /// </summary>
    private string GetStatusDescription(OrderApplicationStatus status)
    {
        return status switch
        {
            OrderApplicationStatus.Draft => "草稿",
            OrderApplicationStatus.Pending => "待支付",
            OrderApplicationStatus.Paid => "已支付",
            OrderApplicationStatus.Progress => "进行中",
            OrderApplicationStatus.Completed => "已完成",
            OrderApplicationStatus.Cancelled => "已取消",
            _ => "未知状态"
        };
    }
}